<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Requests\SupplementSheetRequest;
use App\Models\MatchOrder;
use App\Models\Traits\UploadsHelper;
use App\Transformers\MatchOrderTransformer;
use Dingo\Api\Exception\ResourceException;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class SupplementSheetController extends Controller
{
    // 这里需要一个策略类 是不是当前用户
    public function index(Request $request,$type)
    {
        $user = auth('api')->user();
        $tradeQueueId = $request->trade_queue_id;
        if($type == 'withdraw') {
            //$trade_queue = 'withdraw_trade_queue_id';
            $matchOrders = $user->tradeQueues->where('id',$tradeQueueId)->first()->matchOrderDeposit;
        }else {
            //$trade_queue = 'deposit_trade_queue_id';
            $matchOrders = $user->tradeQueues->where('id',$tradeQueueId)->first()->matchOrderWithDraw;
        }
        return $this->response->collection($matchOrders,new MatchOrderTransformer());
    }

    // 收款 | 付款  注意用户操作
    public function store(SupplementSheetRequest $request,$type)
    {
        $user = auth('api')->user();
        $matchOrderId = $request->match_order_id;
        $matchOrder = MatchOrder::findOrFail($matchOrderId);
        if($type == 'withdraw') {
            //
            if($matchOrder->withdraw_confirm_at) {
                throw new ResourceException('error',[['error_code'=>'500002','message'=>'提现人已确认收款，无需重复确认！']]);
            }
            $tradeQueue = $user->tradeQueues->where('id',$matchOrder->withdraw_trade_queue_id)->where('type',$type)->first();
            if(!$tradeQueue) {
                throw new ResourceException('error',[['error_code'=>'500002','message'=>'提现人确认收款，非法操作！']]);
            }

            $matchOrder = $tradeQueue->matchOrderWithDraw->where('id',$matchOrderId)->first()->update([
                'withdraw_confirm_at' => time()
            ]);

        }else {
            if($matchOrder->deposit_confirm_at) {
                throw new ResourceException('error',[['error_code'=>'500002','message'=>'发起人已确认付款，无需重复确认！']]);
            }
            $tradeQueue = $user->tradeQueues->where('id',$matchOrder->deposit_trade_queue_id)->where('type',$type)->first();
            if(!$tradeQueue) {
                throw new ResourceException('error',[['error_code'=>'500002','message'=>'发起人确认付款，非法操作！']]);
            }
            $depositProofImg = $request->file('deposit_proof_img_url')->store('/public/' . date('Y-m-d') . '/deposit_proof_img');
            //上传的头像字段avatar是文件类型
            $depositProofImgUrl = \Storage::url($depositProofImg);//就是很简单的一个步骤
            $matchOrder = $tradeQueue->matchOrderDeposit->where('id',$matchOrderId)->first()->update([
                'deposit_confirm_at' => time(),
                'deposit_proof_img_url' => $depositProofImgUrl
            ]);
        }
        return $this->response->array($matchOrder)->setStatusCode(201);
    }
}
